package example.com.nexd.collectionsdk.sdk.collector;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.util.Timer;

import example.com.nexd.collectionsdk.sdk.collector.listener.TimerTaskListener;
import example.com.nexd.collectionsdk.sdk.core.TaskExecutor;
import example.com.nexd.collectionsdk.sdk.utils.MD5Util;


/**
 * UserIdUtils create by codingfish at 15/4/23
 * TODO:
 *
 * @Version V1.0
 */
public class UserIdUtils {
    private long time;
    private Timer timer;

    private String task_Id = "";
    private TimerTaskListener timerTaskListener;

    private UserIdUtils() {
        time = System.currentTimeMillis();
        task_Id = MD5Util.parseStrToMd5L16(Long.toString(time));
    }

    public static UserIdUtils getInstance() {
        return SingletonHolder.getInstance();
    }

    public String getMacAddress(Context context) {
        String mac = "";
        // 获取wifi管理器
        WifiManager wifiMng = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfor = wifiMng.getConnectionInfo();
        mac = wifiInfor.getMacAddress();
        return mac;
    }


    public void setTimerTaskListener(TimerTaskListener timerTaskListener) {
        this.timerTaskListener = timerTaskListener;
    }

    public void startTaskId(CollectorConfig collectorConfig, Context context) {
        timer = TaskExecutor.startTimerTask(new TaskIdRunnable(context), 0, collectorConfig.collector_task_delay);
    }

    public void stopTaskId() {
        if (timer != null) {
            timer.cancel();
        }
    }

    public String getUserId(Context context) {
        return MD5Util.parseStrToMd5L32(getMacAddress(context));
    }

    public String getTask_Id() {
        return task_Id;
    }


    private class TaskIdRunnable implements Runnable {
        private String userId;

        private TaskIdRunnable(Context context) {
            userId = getUserId(context);
        }

        @Override
        public void run() {
            time = System.currentTimeMillis();
            task_Id = MD5Util.parseStrToMd5L16(Long.toString(time) + userId);
            timerTaskListener.timerTaskCallback(task_Id);
        }
    }

    private static class SingletonHolder {
        private static UserIdUtils instance = new UserIdUtils();

        public static UserIdUtils getInstance() {
            return instance;
        }
    }
}
